<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\middleware;

use think\facade\Cache;

class VisitHistory
{
    //记录访问
    public function handle($request, \Closure $next){
        $response = request();
        $ip = $response->ip();
        $url = $response->pathinfo();
        $token = $response->header('Authorization');
        $mall_id = $response->header('mid');
        $array = ['user/tokenToUserInfo','total/uvpv','trolley/count','index/integral/judge'];
        if (!empty($token) && !in_array($url,$array)) {
            $user = Cache::store('redis')->get('INDEX:' . $token);
            $user = json_decode($user);
            if(empty($user) || empty($user->id)) return $next($request);
            if(empty($user->pid))return $next($request);
            $visit = ['ip' => $ip,'url' => 'index/'.$url,'create_time' => time(),'user_id' => $user->id,'merchant_id' => $user->merchant_id ?? 0,'mall_id' => $mall_id,'mode' => $_SERVER['REQUEST_METHOD']];
            writeVisitHistory(json_encode($visit));
        }else{
            return $next($request);
        }
        return $next($request);
    }
}